package com.ds.infrastructure.hyperspace.container.internal.gzs;

import com.ds.infrastructure.hyperspace.common.config.GzsConfig;
import com.ds.infrastructure.hyperspace.container.flow.context.HyperspaceDuplexFlowContext;
import com.ds.infrastructure.zonesdk.Zone;
import com.ds.infrastructure.zonesdk.ZoneClient;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author  Weishaoying
 */
@Slf4j
public class GzsService {

    private final ZoneClient gzsClient;

    private final GzsChangeRegistry gzsChangeRegistry;

    public GzsService(GzsConfig gzsConfig) {
        try {
            List<String> shardingKeyTypeList = gzsConfig.getShardingKeyTypeList();
            String[] shardingKeyTypeArray = new String[shardingKeyTypeList.size()];
            shardingKeyTypeList.toArray(shardingKeyTypeArray);
            this.gzsClient = new ZoneClient(gzsConfig.getUrl(), shardingKeyTypeArray);
            this.gzsChangeRegistry = new GzsChangeRegistry(gzsClient);
        } catch (Exception e) {
            log.error("Init gzsClient failed!", e);
            throw new GzsInitException("Init gzs failed!", e);
        }
    }

    public Zone getZone(String shardingKeyTypeStr, String shardingKey) {
        return gzsClient.getZone(shardingKey, shardingKeyTypeStr);
    }

    public void register(HyperspaceDuplexFlowContext duplexFlowContext) {
        if (duplexFlowContext == null || !duplexFlowContext.getEndpointProtocol().isLongLive() ||
                duplexFlowContext.getShardingKey() == null) {
            return;
        }
        this.gzsChangeRegistry.register(duplexFlowContext);
    }

    public void unRegister(HyperspaceDuplexFlowContext duplexFlowContext) {
        if (duplexFlowContext == null || !duplexFlowContext.getEndpointProtocol().isLongLive() ||
                duplexFlowContext.getShardingKey() == null) {
            return;
        }
        this.gzsChangeRegistry.unRegister(duplexFlowContext);
    }
}
